<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div>
    <div id="title">
      <button data-url="/center">个人中心</button>
      <button data-url="/news">新闻</button>
      <button data-url="/music">音乐</button>
    </div>
    <div id="view"></div>
  </div>
  <script>
    const oBtns = document.querySelectorAll('#title button')
    const oView = document.querySelector('#view')
    //1.创建一个路由表,规定路由的对应信息
    const routes = [
      { path: '/center', content: '个人中心' },
      { path: '/news', content: '新闻' },
      { path: '/music', content: '音乐' }
    ]
    //2.遍历所有的btns,绑定事件
    for (var i = 0; i < oBtns.length; i++) {
      //给所有的btns绑定点击事件
      oBtns[i].onclick = function () {
        //获取当前路由跳转的按钮上保存的path信息,改变地址栏地址的hash值
        location.hash = this.dataset.url
      }
      //通过onhashchange事件监听当前的url的hash值的变化
      window.onhashchange = function (e) {
        const newURL = e.newURL.split('#')[1]
        //拿到当前的hash和路由表汇总的path进行一一对比,更新对应的视图
        routes.forEach(route => {
          if (route.path === newURL) {
            //更新视图
            oView.textContent = route.content
          }
        })
      }
    }


  </script>
</body>

</html>